/**
 *  This file is part of PennerBot
 *
 *  Copyright (C) 2010 microkernel
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <iomanip>
#include <sstream>

#include <console/mainhandler.hpp>

namespace PBot
{
namespace Console
{

Log::Log(const std::string& _name, boost::recursive_mutex& _mutex)
 : name(_name), mutex(_mutex)
{
    file.open(std::string("logs/"+_name+"_log.txt").c_str());
}

Log::~Log()
{
    file.close();
}

void Log::Info(const std::string& str)
{
    Print("[INFO]", str);
}

void Log::Error(const std::string& str)
{
    Print("[ERROR]", str);
}

void Log::Print(const std::string& prefix, const std::string& str)
{
    boost::recursive_mutex::scoped_lock lock(mutex);
    time(&rawtime);

    int hour, minute, seconds;
    timeinfo = localtime(&rawtime);

    hour = timeinfo->tm_hour;
    minute = timeinfo->tm_min;
    seconds = timeinfo->tm_sec;

    std::stringstream formatString;
    formatString << "[" << std::setw(2) << std::setfill('0') << hour << ":" << std::setw(2) << std::setfill('0') << minute << ":" << std::setw(2) << std::setfill('0') << seconds << "]";


    if(name != "main")
    {
        file << formatString.str() << " [" << name << "]" << prefix << " " << str << std::endl;
        std::cout << formatString.str() << " [" << name << "] " << str << std::endl;
    }
    else
    {
        file << formatString.str() << prefix << " " << str << std::endl;
        std::cout << formatString.str() << " " << str << std::endl;
    }
}

}
}
